package cn.wolfcode.car.business.service.impl;

import cn.wolfcode.car.business.domain.*;
import cn.wolfcode.car.business.mapper.*;
import cn.wolfcode.car.business.query.CarPackageAuditQuery;
import cn.wolfcode.car.business.service.ICarPackageAuditService;
import cn.wolfcode.car.business.service.IServiceItemService;
import cn.wolfcode.car.common.base.page.TablePageInfo;
import cn.wolfcode.car.common.exception.BusinessException;
import cn.wolfcode.car.shiro.ShiroUtils;
import com.github.pagehelper.PageHelper;
import org.activiti.bpmn.model.AdhocSubProcess;
import org.activiti.bpmn.model.BpmnModel;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.task.Task;
import org.activiti.image.ProcessDiagramGenerator;
import org.activiti.image.impl.DefaultProcessDiagramGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.InputStream;
import java.util.Collections;
import java.util.Date;
import java.util.List;

@Service
@Transactional
public class CarPackageAuditServiceImpl implements ICarPackageAuditService {

    @Autowired
    private CarPackageAuditMapper carPackageAuditMapper;
    @Autowired
    private CarPackageAuditHistoryMapper carPackageAuditHistoryMapper;
    @Autowired
    private BpmnInfoMapper bpmnInfoMapper;
    @Autowired
    private RepositoryService repositoryService;
    @Autowired
    private TaskService taskService;
    @Autowired
    private RuntimeService runtimeService;
    @Autowired
    private ServiceItemMapper serviceItemMapper;

    @Override
    public TablePageInfo<CarPackageAudit> query(CarPackageAuditQuery qo) {
        PageHelper.startPage(qo.getPageNum(), qo.getPageSize());
        return new TablePageInfo<CarPackageAudit>(carPackageAuditMapper.selectForList(qo));
    }


    @Override
    public void save(CarPackageAudit carPackageAudit) {
        carPackageAuditMapper.insert(carPackageAudit);
    }

    @Override
    public CarPackageAudit get(Long id) {
        return carPackageAuditMapper.selectByPrimaryKey(id);
    }


    @Override
    public void update(CarPackageAudit carPackageAudit) {
        carPackageAuditMapper.updateByPrimaryKey(carPackageAudit);
    }

    @Override
    public void deleteBatch(Long id) {
        carPackageAuditMapper.deleteByPrimaryKey(id);
    }

    @Override
    public List<CarPackageAudit> list() {
        return carPackageAuditMapper.selectAll();
    }

    @Override
    public InputStream getProcessImageByAuditId(Long id) {
        CarPackageAudit audit = carPackageAuditMapper.selectByPrimaryKey(id);
        BpmnInfo bpmnInfo = bpmnInfoMapper.selectByPrimaryKey(audit.getBpmnInfoId());
        InputStream inputStream = null;
        //流程文件使用代码方式画出来
        BpmnModel model = repositoryService.getBpmnModel(bpmnInfo.getActProcessId());
        ProcessDiagramGenerator generator = new DefaultProcessDiagramGenerator();
        //1:审核中
        if (CarPackageAudit.STATUS_IN_ROGRESS.equals(audit.getStatus())) {

            Task task = taskService.createTaskQuery()
                    .processInstanceId(audit.getInstanceId()).singleResult();
            List<String> activeActivityIds =
                    runtimeService.getActiveActivityIds(task.getExecutionId());

            inputStream = generator.generateDiagram(model, activeActivityIds,
                    Collections.EMPTY_LIST,
                    "宋体", "宋体", "宋体");
        } else {
            //2：审核结束
            inputStream = generator.generateDiagram(model, Collections.EMPTY_LIST, Collections.EMPTY_LIST,
                    "宋体", "宋体", "宋体");
        }
        return inputStream;

    }

    // 撤销流程审核
    @Override
    public void cancelApply(Long id) {
        // 撤销的条件：流程在审核中
        // 撤销流程审核：服务项的状态要回到初始化，审核记录业务表要改为撤销状态，审核流程实例要删除
        CarPackageAudit audit = carPackageAuditMapper.selectByPrimaryKey(id);
        if (!CarPackageAudit.STATUS_IN_ROGRESS.equals(audit.getStatus())) {
            throw new BusinessException("只有在审核中的状态才可以撤销");
        }
        // 恢复套餐服务项的审核状态初始化
        serviceItemMapper.changeAuditStatus(audit.getServiceItemId(), ServiceItem.AUDITSTATUS_INIT);
        // 审核记录业务表的状态改为撤销状态
        carPackageAuditMapper.changeStatus(id, CarPackageAudit.STATUS_CANCEL);
        // 流程实例删除：通过流程实例id
        runtimeService.deleteProcessInstance(audit.getInstanceId(), "审核被撤销。");

    }

    @Override
    // 流程审核
    public void audit(Long id, Integer auditStatus, String info) {
        // 判断是否满足流程审核条件：审核中,且当前登录的用户是审核人
        CarPackageAudit audit = carPackageAuditMapper.selectByPrimaryKey(id);
        if (audit == null || !CarPackageAudit.STATUS_IN_ROGRESS.equals(audit.getStatus())
                || !audit.getAuditorId().equals(ShiroUtils.getUser().getId())) {
            throw new BusinessException("只有审核中状态才可以进行审核");
        }
        String AuditorInfo = info;
        // 保存到流程审核记录历史表中：
        CarPackageAuditHistory auditHistory = new CarPackageAuditHistory();

        // 获取当前审核人：
        String userName = ShiroUtils.getUser().getUserName();
        // 如果状态为2，则同意
        if (auditStatus == 2) {
            info += "[ " + userName + " 同意]";
        } else {
            info += "[ " + userName + " 拒绝]";

        }
        // 设置流程审核记录表里的审核备注
        audit.setInfo(audit.getInfo() + "<br>" + info);
        // 设置流程审核记录业务表的当前审核时间
        audit.setAuditTime(new Date());

        auditHistory.setCarPackageAuditId(audit.getId());
        auditHistory.setServiceItemId(audit.getServiceItemId());
        auditHistory.setServiceItemInfo(audit.getServiceItemInfo());
        auditHistory.setServiceItemPrice(String.valueOf(audit.getServiceItemPrice()));
        auditHistory.setInstanceId(Long.valueOf(audit.getInstanceId()));
        auditHistory.setCreator(audit.getCreator());
        auditHistory.setAuditorId(ShiroUtils.getUserId());
        auditHistory.setBpmnInfoId(audit.getBpmnInfoId());
        auditHistory.setInfo(AuditorInfo);

        auditHistory.setAuditTime(new Date());
        auditHistory.setCreateTime(audit.getCreateTime());

        // 执行当前的排他网关节点:
        Task task = taskService.createTaskQuery()
                .processInstanceId(audit.getInstanceId())
                .singleResult();
        // 设置审核操作的同意与否的参数：
        // 流程图中约定了：如果 auditstatus = 2,则为同意通过，否则为拒绝
        taskService.setVariable(task.getId(), "auditStatus", auditStatus);
        // 设置审核备注：1、任务id，2、流程实例id，3、执行任务时的备注
        taskService.addComment(task.getId(), audit.getInstanceId(), info);
        // 执行节点审核
        taskService.complete(task.getId());

        // 获取下一个节点，判断还有没有下一步节点
        Task nextTask = taskService.createTaskQuery()
                .processInstanceId(audit.getInstanceId())
                .singleResult();

        // 审核通过逻辑
        if (CarPackageAudit.STATUS_PASS.equals(auditStatus)) {
            // 如果有下一个节点：修改流程审核记录表的审核人（财务）
            if (nextTask != null) {
                audit.setAuditorId(Long.parseLong(nextTask.getAssignee()));
                auditHistory.setStatus(CarPackageAuditHistory.STATUS_IN_ROGRESS);
            } else {
                // 如果没有下一个节点：流程结束
                // 设置套餐服务项的审核状态：
                serviceItemMapper.changeAuditStatus(audit.getServiceItemId(), ServiceItem.AUDITSTATUS_APPROVED);
                // 流程审核记录表的状态：通过
                audit.setStatus(CarPackageAudit.STATUS_PASS);
                auditHistory.setStatus(CarPackageAuditHistory.STATUS_PASS);
            }
        } else {
            // 审核拒绝逻辑：
            // 把套餐服务单项状态改为为审核拒绝(这里设置为初始化)
            serviceItemMapper.changeAuditStatus(audit.getServiceItemId(), ServiceItem.AUDITSTATUS_INIT);
            // 把流程审核记录表的状态该为审核拒绝
            audit.setStatus(CarPackageAudit.STATUS_REJECT);
            auditHistory.setStatus(CarPackageAuditHistory.STATUS_REJECT);
        }
        carPackageAuditMapper.updateByPrimaryKey(audit);
        carPackageAuditHistoryMapper.insert(auditHistory);
    }
}
